package com.cuz.hot100;

public class Q7integerReverse {

    static class Solution {
        public static void main(String[] args) {
            System.out.println(new Solution().reverse(-2147483648));
        }

        public int reverse(int x) {
            if (Math.abs(x) < 10) {
                return x;
            }

            int result = 0;
            int max10 = Integer.MAX_VALUE / 10;
            int maxLast = Integer.MAX_VALUE % 10;
            int min10 = Integer.MIN_VALUE / 10;
            int minLast = Integer.MIN_VALUE % 10;
            while (x != 0) {
                int last = x % 10;
                x = x / 10;

                if (result > max10) {
                    return 0;
                }
                if (result == max10 && last > maxLast) {
                    return 0;
                }
                if (result < min10) {
                    return 0;
                }
                if (result == min10 && last < minLast) {
                    return 0;
                }
                result = result * 10 + last;
            }
            return result;
        }
    }

    public static void main(String[] args) {
        System.out.println(reverse1(891));
        System.out.println(reverse1(1534236469));
        System.out.println(reverse1(102));
    }

    public static int reverse1(int x) {
        boolean isNegative = x < 0;
        x = Math.abs(x);
        int res = 0;
        int digits = digitsOf(x);
        int curDig = 0;
        int tenPow;
        int shouldAdd;
        while (curDig < digits) {
            tenPow = (int) Math.pow(10, digits - curDig - 1);
            int temp = (x / tenPow);
            x = x % tenPow;
            shouldAdd = (int) (Math.pow(10, curDig++) * temp);
            if (res + shouldAdd < 0) {
                return 0;
            }
            res += shouldAdd;
        }
        shouldAdd = (int) (Math.pow(10, curDig) * x);
        if (res + shouldAdd < 0) {
            return 0;
        }
        res += shouldAdd;
        return isNegative ? -res : res;
    }


    private static int digitsOf(int x) {
        int res = 0;
        while (x > 9) {
            x = x / 10;
            res++;
        }
        return res + 1;
    }

}
